package controller

import (
	"fmt"
	"imooc.com/hello/model"
	"imooc.com/hello/service"
	"imooc.com/hello/util"
	"math/rand"
	"net/http"
	"strconv"
)
var userService service.UserService

func UserLogin(writer http.ResponseWriter,
	request *http.Request) {
	//数据库操作
	//逻辑处理
	//rest api json/xml返回
	//获取参数
	//post/put/patch请求获取,这种方式必须是application/x-www-form-urlencoded传递才行
	request.ParseForm() //解析参数
	mobile := request.PostForm.Get("mobile")
	password := request.PostForm.Get("password")
	//get请求
	//username := request.URL.Query().Get("username")
	//password := request.URL.Query().Get("password")

	user, err := userService.Login(mobile, password)
	if err != nil {
		util.RespFail(writer, err.Error())
	}else {
		util.RespOk(writer, user, "登录成功")
	}
}

func UserRegister(writer http.ResponseWriter,
	request *http.Request)  {

	request.ParseForm() //解析参数
	mobile := request.PostForm.Get("mobile")
	plainpwd := request.PostForm.Get("password")
	nickname := fmt.Sprintf("user%06d", rand.Int31())
	avatar := ""
	sex := model.SEX_UNKNOW

	user, err := userService.Register(mobile, plainpwd, nickname,
		avatar, sex)
	if err != nil {
		util.RespFail(writer,  err.Error())
	}else {
		util.RespOk(writer, user,  "注册成功")
	}
}

func UserFind(writer http.ResponseWriter, request *http.Request)  {
	request.ParseForm()
	id := request.PostForm.Get("id")
	if id == "" {
		util.RespFail(writer,  "参数不正确")
		return
	}
	userId, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		util.RespFail(writer,  err.Error())
		return
	}
	user, err := userService.LoadById(userId)
	if err != nil {
		util.RespFail(writer,  err.Error())
	}else {
		util.RespOk(writer, user,  "")
	}
}
